import router from '@/router'
import { useUserStore, useSystemStore } from '@/stores'
const userStore = useUserStore()
const systemStore = useSystemStore()

//当不传path参数时，path为当前路由值
const can = (permissionCode: string, path = null) => {
  if (userStore.id <= 0) {
    return true;
  }
  if (!path) {
    path = router.history.current.path;
  }
  return systemStore.permissionMenus.some(item => {
    if (item.fullPath == path || item.permissionPath == path) {
      if (item.isPage) {
        let parentMenu = systemStore.permissionMenus.find(i => i.id == item.parentId);
        return parentMenu && parentMenu.permissionCodes.some(code => code == permissionCode)
      }
      return (item.permissionCodes || []).some(code => code == permissionCode)
    }
  })
}


//是否有读权限
const canRead = (path = null) => {
  return can("canRead", path);
}
//是否有写权限
const canWrite = (path = null) => {
  return can("canWrite", path);
}
//是否有审核权限
const canReview = (path = null) => {
  return can("canReview", path);
}

//是否有某个菜单
const hasMenu = (path: string) => {
  if (userStore.id <= 0) {
    return true;
  }
  return systemStore.permissionMenus.some(item => item.fullPath == path || item.permissionPath == path);
}
export {
  can,
  canRead,
  canWrite,
  canReview,
  hasMenu
}